package com.wms.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wms.pojo.Category;
import com.wms.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Controller
@RequestMapping("/category")
public class CategoryController {


    @Autowired
    private CategoryService categoryService;

    @GetMapping("/getCategories")
    public String getCategories(@RequestParam(defaultValue = "1")Integer pageNum,@RequestParam(defaultValue = "5") Integer pageSize, Model model){
        PageHelper.startPage(pageNum,pageSize);
        List<Category> categories = categoryService.queryAll();
        PageInfo pageInfo = new PageInfo(categories);
        model.addAttribute("pageInfo",pageInfo);
        return "wine/category-list";
    }

    @GetMapping("/deleteCategory")
    public String deleteCategory(@RequestParam("id") Integer id){
        categoryService.deleteCategory(id);
        return "redirect:/category/getCategories";
    }

    @PostMapping("/addCategory")
    public String addCategory(Category category){
        categoryService.addCategory(category);
        return "redirect:/category/getCategories";
    }

    @GetMapping("/toEdit")
    public String toEdit(@RequestParam("id") Integer id,Model model){
        Category category = categoryService.queryById(id);
        model.addAttribute("category",category);
        return "wine/category-edit";
    }

    @PostMapping("/updateCategory")
    public String updateCategory(Category category){
        categoryService.updateCategory(category);
        return "redirect:/category/getCategories";
    }
}
